package com.bluefox.uac.filter;

import com.bluefox.common.web.dto.result.ResultDTO;
import com.bluefox.common.web.utils.JsonUtils;
import com.bluefox.uac.security.CustomAuthenticationToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * @author SF  创建时间: 2019/12/4 17:49
 */

public class DefaultLogoutSuccessHandler implements LogoutSuccessHandler {
    private final Log logger = LogFactory.getLog(this.getClass());

    @Override
    public void onLogoutSuccess(final HttpServletRequest request, final HttpServletResponse response,
                                final Authentication authentication) throws IOException, ServletException {
        if (authentication != null) {
            final String nonceToken = ((CustomAuthenticationToken) authentication).getNonceToken();
            if (StringUtils.hasText(nonceToken)) {
                // 删除一次性token
                ((CustomAuthenticationToken) authentication).setToken(null, 0L);
                // 清空session
                /**
                 * request.getSession(true).removeAttribute("saml.userid");
                 */
                SecurityContextHolder.clearContext();  //清空上下文
            }
        }

        if (response.isCommitted()) {
            this.logger.debug("Response has already been committed. ");
            return;
        } else {
            final ResultDTO<?> logoutResp = ResultDTO.success();
            final Writer writer = response.getWriter();
            writer.write(JsonUtils.pojoToJson(logoutResp));
            writer.flush();
            writer.close();
        }
    }
}
